package com.kfm.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.*;
import java.util.Base64;

/**
 * @Author yangbohan
 * @Date 2023/10/21 9:56
 */

public class Login extends HttpServlet {
    public static final String url = "jdbc:mysql://localhost:3306/kfm_date";
    public static final String db_user = "root";
    public static final String db_password = "";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 验证用户密码
        boolean isValid = validatePassword(username, password);
        if (isValid) {
            response.getWriter().println("密码验证通过");
        } else {
            response.getWriter().println("密码验证未通过");
        }
    }

    private boolean validatePassword(String username, String password) {
        try (Connection connection = DriverManager.getConnection(url, db_user, db_password);) {
            // 获取数据库获取用户的盐值
            byte[] salt = getSaltFromDatabase(username);
            // 对用户输入的密码进行加盐哈希计算
            byte[] hashedPassword = hashPassword(password, salt);
            // 从数据库中获取存储的哈希密码
            byte[] storedPassword = getStoredPasswordFromDatabase(username);
            // 进行密码的比较
            return MessageDigest.isEqual(hashedPassword, storedPassword);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private byte[] getStoredPasswordFromDatabase(String username) {
        try (Connection connection = DriverManager.getConnection(url, username, db_password);
             PreparedStatement statement = connection.prepareStatement("SELECT password FROM users WHERE username = ?")) {
            statement.setString(1, username);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    String passwordStr = resultSet.getString("password");
                    return Base64.getDecoder().decode(passwordStr);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] hashPassword(String password, byte[] salt) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(salt);
            byte[] hashedBytes = messageDigest.digest(password.getBytes(StandardCharsets.UTF_8));
            return hashedBytes;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private byte[] getSaltFromDatabase(String username) {
        try (Connection connection = DriverManager.getConnection(url, db_user, db_password);
             PreparedStatement statement = connection.prepareStatement("SELECT salt FROM users WHERE username = ?")) {
            statement.setString(1, username);
            try (ResultSet resultSet = statement.executeQuery()) {
                if (resultSet.next()) {
                    String saltStr = resultSet.getString("salt");
                    return Base64.getDecoder().decode(saltStr);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
